package com.fjwt.gz.task.mch;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjwt.gz.db.dto.MchInfoDTO;
import com.fjwt.gz.db.dto.PointDTO;
import com.fjwt.gz.db.entity.MchChannelEntity;
import com.fjwt.gz.db.entity.MchInfoEntity;
import com.fjwt.gz.pay.mch.mchinfo.MchInfoResponseData;
import com.fjwt.gz.pay.mch.mchinfo.MchInfoSyncService;
import com.fjwt.gz.service.impl.MchChannelService;
import com.fjwt.gz.service.impl.MchInfoService;
import com.fjwt.gz.task.util.SysDateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class SyncMchInfoTask {
    @Autowired
    private MchInfoSyncService mchInfoSyncService;
    @Autowired
    private MchInfoService mchInfoService;
    @Autowired
    private MchChannelService mchChannelService;


//    @Scheduled(cron = "${cron.SyncMchInfoTask}")//每天定时1点
    @Transactional
    public void start() {
        log.info("开始进入同步商户信息定时任务,任务开始时间:{}", DateUtil.now());
        Date date = new Date();
        DateTime offset = DateUtil.offset(date, DateField.DAY_OF_MONTH, -1);
        //昨日零点
        DateTime yesterdayZero = SysDateUtil.getToday(offset);
        //今日零点
        DateTime todayZero = SysDateUtil.getToday(DateUtil.date());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String yesterday = simpleDateFormat.format(yesterdayZero);
        String today = simpleDateFormat.format(todayZero);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("applyUpdateTimeStart", yesterday);
        jsonObject.put("applyUpdateTimeEnd", today);

        jsonObject.put("pageSize", 100);

        int currentPageIndex = 1; //当前页码
        while (true) {

            try {
                jsonObject.put("pageNumber", currentPageIndex);
                log.info("【同步商户信息】，请求数据：{}", JSONUtil.toJsonStr(jsonObject));
                MchInfoResponseData mchInfoResponseData = mchInfoSyncService.getMchInfos(jsonObject);
                List<String> records = mchInfoResponseData.getRecords();

                if (CollUtil.isEmpty(records)) { //本次查询无结果, 不再继续查询;
                    log.info("同步商户信息定时任务，后面没有数据，跳出循环");
                    break;
                }

                for (String str : records) {
                    log.info("str:{}", str);
                    JSONObject strJson = JSONObject.parseObject(str);
                    String userType = strJson.getString("userType");
                    if (!"1".equals(userType)){
                        log.info("此时数据不是商户的超级管理员，直接下一条");
                        continue;
                    }

                    // 正则去除时间类型后六位微秒
                    str = str.replaceAll("(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2})\\.\\d{6}\"", "$1\"");

                    MchInfoDTO mchInfoDTO = JSONObject.parseObject(str, MchInfoDTO.class);
                    MchInfoEntity mchInfoDb = mchInfoService.getById(mchInfoDTO.getMchNo());
                    mchInfoDTO.setPhone(strJson.getString("telphone"));
                    MchInfoEntity mchInfo = new MchInfoEntity();
                    mchInfo.setMchNo(mchInfoDTO.getMchNo());
                    if (ObjectUtil.isEmpty(mchInfoDb)) {
                        BeanUtils.copyProperties(mchInfoDTO,mchInfo);
                        mchInfo.setLocation(new PointDTO(new BigDecimal(mchInfoDTO.getLng()), new BigDecimal(mchInfoDTO.getLat())));
                        log.info("新增商户信息：商户号：{},商户信息：{}", mchInfo.getMchNo(), JSONUtil.toJsonStr(mchInfo));
                        mchInfoService.addMchInfo(mchInfo);
                    } else {
                        MchInfoEntity mchInfoSave = new MchInfoEntity();
                        BeanUtils.copyProperties(mchInfoDTO,mchInfoSave);
                        mchInfoSave.setLocation(new PointDTO(new BigDecimal(mchInfoDTO.getLng()), new BigDecimal(mchInfoDTO.getLat())));
                        mchInfoSave.setMchBannerImage(mchInfoDTO.getBannerImageUrl());
                        log.info("更新商户信息：商户号：{},商户信息：{}", mchInfo.getMchNo(), JSONUtil.toJsonStr(mchInfo));
                        mchInfoService.updateMchInfoById(mchInfoSave);
                    }
                    MchChannelEntity mchChannelEntity = JSONObject.parseObject(str, MchChannelEntity.class);
                    LambdaQueryWrapper<MchChannelEntity> gw = MchChannelEntity.gw();
                    gw.eq(MchChannelEntity::getMchNo, mchChannelEntity.getMchNo());
                    gw.eq(MchChannelEntity::getChannelDiyMchNo, mchChannelEntity.getChannelDiyMchNo());
                    MchChannelEntity mchChannelEntityDb = mchChannelService.getOne(gw);

                    Boolean inUse = strJson.getBoolean("inUse");
                    if (inUse) {
                        mchChannelEntity.setState(1);
                        log.info("【此处通道信息为状态-->正在使用】");
                        if (ObjectUtil.isEmpty(mchChannelEntityDb)) {
                            log.info("新增商户通道信息：商户号：{}，三方商户号：{}", mchInfo.getMchNo(), mchChannelEntity.getChannelDiyMchNo());
                            updateDbList(mchChannelEntity.getMchNo());
                            mchChannelService.save(mchChannelEntity);
                        } else {
                            log.info("更新商户通道信息：商户号：{}，三方商户号：{}", mchInfo.getMchNo(), mchChannelEntityDb.getChannelDiyMchNo());
                            mchChannelEntity.setMchChannelId(mchChannelEntityDb.getMchChannelId());
                            updateDbList(mchChannelEntity.getMchNo());
                            mchChannelService.updateById(mchChannelEntity);
                        }
                    } else {
                        mchChannelEntity.setState(0);
                        log.info("【此处通道信息为状态-->未使用】");
                        if (ObjectUtil.isEmpty(mchChannelEntityDb)) {
                            log.info("新增商户通道信息：商户号：{}，三方商户号：{}", mchInfo.getMchNo(), mchChannelEntity.getChannelDiyMchNo());
                            mchChannelService.save(mchChannelEntity);
                        } else {
                            mchChannelEntity.setMchChannelId(mchChannelEntityDb.getMchChannelId());
                            log.info("更新商户通道信息：商户号：{}，三方商户号：{}", mchInfo.getMchNo(), mchChannelEntity.getChannelDiyMchNo());
                            mchChannelService.updateById(mchChannelEntity);
                        }
                    }
                }
                Thread.sleep(20000);
                currentPageIndex++;
            } catch (Exception e) { //出现异常，直接退出，避免死循环。
                log.error("error", e);
                break;
            }
        }
    }

    private void updateDbList(String mchNo) {
        LambdaQueryWrapper<MchChannelEntity> gwSave = MchChannelEntity.gw();
        gwSave.eq(MchChannelEntity::getMchNo, mchNo);
        gwSave.eq(MchChannelEntity::getState, 1);
        List<MchChannelEntity> dbList = mchChannelService.list(gwSave);
        if (CollUtil.isEmpty(dbList)) {
            return;
        }
        for (MchChannelEntity en : dbList) {
            en.setState(0);
            mchChannelService.updateById(en);
        }
        log.info("此为新增新的当前进件通道，更新之前使用过的通道为未使用");
    }

}
